
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:reabampos/src/reabam/operation/bean/check_app_update/Request_check_app_update.dart';
import 'package:reabampos/src/reabam/operation/bean/login_response.dart';
import 'package:reabampos/src/reabam/operation/db/objectbox.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/operation/rb_enum.dart';
import 'package:reabampos/src/reabam/ui/chengzhong/pagestate_chengzhong.dart';
import 'package:reabampos/src/reabam/ui/pagestate_other_webview.dart';
import 'package:reabampos/src/reabam/ui/pagestate_scan_qr_code.dart';
import 'package:reabampos/src/reabam/ui/setting/pagestate_setting_device.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/ui/support/support_download_db_file.dart';
import 'package:reabampos/src/reabam/ui/support/support_get_good_items.dart';
import 'package:reabampos/src/reabam/ui/support/support_h5_api_cache.dart';
import 'package:reabampos/src/reabam/ui/support/support_offline_cuxiao.dart';
import 'package:reabampos/src/reabam/ui/support/support_offline_order.dart';
import 'package:reabampos/src/reabam/ui/support/support_control_devices.dart';
import 'package:reabampos/src/reabam/ui/support/support_repay_order.dart';
import 'package:reabampos/src/reabam/ui/support/support_upload_order_paylist.dart';
import 'package:reabampos/src/reabam/ui/support/support_handle_photo.dart';
import 'package:reabampos/src/reabam/ui/update_app/pagestate_update_app.dart';
import 'package:reabampos/src/reabam/utils/rb_aliyun_log.dart';
import 'package:reabampos/src/reabam/utils/rb_color.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_aliyun_log.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';
import 'package:xsdk_flutter_plugin/xsdk_flutter_plugin.dart';


/*
注意:如闪退则支付宝smile不兼容导致
 */
class MainWebViewStatePage extends XPageWebViewState{


  MainWebViewStatePage(
      {
        super.desktopNewWindowTitle='睿本云HD',
        super.openDevTools=false,
      }
      );



  @override
  String getWebUrl() {
    String webUrl=_getH5Url();
    XLogUtils.printLog('---webUrl=$webUrl');
    return webUrl;
  }

  @override
  bool getCanHardwarePressBack(){
    return false;
  }

  @override
  bool getIsResizeToAvoidBottomInset() {
    return false;
  }

  @override
  void onStart() {
  }

  //设置h5 url
  String _getH5Url(){
    if(RBConfigs.versionType==VersionType.officialVersion){
      //正式版
      RBConfigs.h5Url= 'https://hd.reabam.com/index.html?t=';
      //RBConfigs.secondScreenWebUrl= 'https://pos-android.reabam.com/#/standard/secondScreen.html';
      RBConfigs.secondScreenWebUrl= 'https://pos.reabam.com/#/standard/secondScreen.html';
    }else if(RBConfigs.versionType==VersionType.baodaoVersion){
      //包道正式版
      RBConfigs.h5Url= 'https://hd.reabam.com/index.html?t=';
      RBConfigs.secondScreenWebUrl= 'https://pos.reabam.com/#/standard/secondScreen.html';
    }else if(RBConfigs.versionType==VersionType.bluegreenVersion){
      //蓝绿版
      RBConfigs.h5Url= 'https://pos2.reabam.com/index.html?t=';
      RBConfigs.secondScreenWebUrl= 'https://pos2.reabam.com/#/standard/secondScreen.html';
    }else if(RBConfigs.versionType==VersionType.testVersion){
      //测试版
      RBConfigs.h5Url= 'http://fat-hd.reabam.com:58090/index.html?t=';
      RBConfigs.secondScreenWebUrl= 'http://fat-pos.reabam.com:58090/#/standard/secondScreen.html';
    }else if(RBConfigs.versionType==VersionType.developerVersion){
      //开发板
      //RBConfigs.h5Url= 'http://192.168.2.177:8056/index.html?t=';//志超
      RBConfigs.h5Url= 'http://192.168.2.177:8055/index.html?t=';//志超
      //RBConfigs.h5Url= 'http://192.168.2.193:8055/index.html?t=';//结昌
      RBConfigs.secondScreenWebUrl= 'http://192.168.2.177:8055/#/standard/secondScreen.html';
    }

    //
    String ptype="mop";
    if(RBConfigs.versionType==VersionType.baodaoVersion){
      //包道
      ptype="baodao";
    }

    RBConfigs.h5Url='${RBConfigs.h5Url}${XDateUtils.getCurrentTime_ms()}&ptype=$ptype';

    return RBConfigs.h5Url;
  }

  late SupportRepayOrder supportRepayOrder;
  late SupportOfflineCuxiao supportOfflineCuxiao;
  late SupportH5ApiCache supportH5ApiCache;
  late SupportOfflineOrder supportOfflineOrder;
  late SupportHandlePhoto supportHandlePhoto;

  @override
  void onCreate() {
    super.onCreate();

    //初始化android设备(商米机等)
    _initAndroid();

    //获取服务端时间
    _checkServerTime();

    //文字转语音
    XTTSUtils.initTts(rate:XFlutterUtils.isiOS()?0.5:1);

    desktopIndexPageCenterWidget= XImageUtils.getImageWidgetWithAsset(
        'welcome_app.png',
        width: 122,
        height: 32.5
    );

    //
    SupportControlDevices.init(this);
    supportRepayOrder=SupportRepayOrder(this);
    supportOfflineCuxiao=SupportOfflineCuxiao(this);
    supportH5ApiCache=SupportH5ApiCache(this);
    supportOfflineOrder=SupportOfflineOrder(this);
    supportHandlePhoto=SupportHandlePhoto(this);

    _getWifiIP();

  }

  void _getWifiIP() async{
    RBConfigs.localIP=await XWifiUtils.getWifiIP();
    XLogUtils.printLog('---localIP=${RBConfigs.localIP}');
  }

  //启用web server api方式通讯
  XWebServer? webServer;
  void _startWebServer(){
    if(webServer==null){
      webServer=XWebServer();
      Map<String,Function> customPostRequestRouterMap={};
      //customPostRequestRouterMap['/setpcvalue']=WebServerRouter(supportUploadOrderAndPay).getRouterHander_Setpcvalue();
      webServer?.start(
        port:8182,
        customPostRequestRouterMap: customPostRequestRouterMap,
      );
    }
  }


  void _checkServerTime(){

    String zuul=XSharePreferencesUtils.getString(RBConfigs.SP_zuulServerAddress);
    if(!XStringUtils.isEmpty(zuul)){
      RBBaseApi.getServerTime(
          succeed: (response, Map<String, dynamic> responseMap, Map<String, dynamic> headersResponse) {
            double longt=XNumberUtils.dynamic2double(responseMap['data'])??0.0;
            if(longt>0){
              double dif=(longt-XDateUtils.getCurrentTime_ms()).abs();
              //XLogUtils.printLog('---difTime=$dif');
              if(dif>10*60*1000){
                XFlutterUtils.openAlertDialogDefault(
                    context: context,
                    title: '设备时间',
                    contentStr: '当前设备时间有误,请校准后再使用?',
                    isShowCancelButton: false,
                    onCallbackResult: (String? bt){
                      if('确定'==bt){
                        XFlutterUtils.closeApp();
                      }
                    }
                );
              }

            }
          },
          failed: (String code, String msg) {
            //
          });
    }

  }

  //初始化android设备(商米机等)
  void _initAndroid() async{

    if(XFlutterUtils.isAndroid()){

      reSetReceiveNativeMessageCallback_XSDKFlutterPlugin();

      //
      Map<String, dynamic> deviceInfo= await XFlutterUtils.getDeviceInfo();
      XLogUtils.printLog('---Android deviceInfo= $deviceInfo');
      dynamic brand =  deviceInfo['brand'];
      dynamic model =  deviceInfo['model'];
      dynamic version =  deviceInfo['version'];

      //初始化支付宝碰一碰设备sdk,参数固定
      Map<String,Object> map_alipayiot={};
      map_alipayiot['appId']='2021004177679101';
      map_alipayiot['pId']='2088611935241475';

      //
      if(XStringUtils.equalsIgnoreCase('SUNMI', brand)){
        //初始化商米机
        XLogUtils.printLog('---初始化商米机');
        RBConfigs.isShangMiDevice=true;
        XFlutterPluginUtils.initShangMiSDK();

        //是否使用商米打印
        RBConfigs.isUserShangMiPrint=XSharePreferencesUtils.getBool(RBConfigs.SP_isUseShangMiPrinter,defaultValue: true);
        RBConfigs.isUserShangMiSerialWeigher=XSharePreferencesUtils.getBool(RBConfigs.SP_isUseShangMiSerialWeigher,defaultValue: true);

        if('$model'.startsWith('T1')||'$model'=='T2'){
          //初始化支付宝碰一碰设备sdk,实测D2_d_2nd android 11 崩溃
          XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        }else{
          //实测商米D2_xx android 11初始化正常, 开放其他商米设备初始化,如闪退则smile不兼容导致
          XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        }

      }else if(XStringUtils.equalsIgnoreCase('HUAWEI', brand)){
        //华为平板 初始化支付宝碰一碰设备sdk,实测有些设备闪退,smile不兼容导致
        /*
        cd D:\Android\Sdk\platform-tools
        ./adb devices
        ./adb shell logcat >smile.log
        ./adb -s 192.168.8.98:5555 shell logcat >smile.log
         */

        // if(version=='12'){
        //   //实测华为 android 12 初始化正常
        //   XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
        // }
        //实测华为 android 12 初始化正常, 开放其他华为平板,如闪退则smile不兼容导致
        XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
      }else{
        //开放其他品牌平板,如闪退则smile不兼容导致
        XFlutterPluginUtils.initAlipayIotSDK(XJsonUtils.obj2Json(map_alipayiot));
      }

    }
  }


  /*
  支付宝Iot会员支付参数
  {"appId":"2021003107671848","providerId":"2088611935241475","templateId":"20240830000000005708166000300470","outString":{"group_id":"61FF8013A1FA494DBDCF718CBCB8E05B","company_id":"5ad586a8721e49518998aedef9fd3b5c"}}
  这里的appid为会员支付的itemAppId,并不是用于初始化的appId
   */
  Map<dynamic,dynamic> alipayIotServiceInfoMap={};
  //更新支付宝碰一碰服务参数
  void _updateAlipayIotDeviceServiceInfo(dynamic data){

    if(XFlutterUtils.isAndroid()){
      alipayIotServiceInfoMap.clear();
      if(data is String){
        alipayIotServiceInfoMap=XJsonUtils.json2Map(data);
      }else if(data is Map){
        alipayIotServiceInfoMap=data;
      }
    }

  }


  //支付宝碰一碰设备取消
  void _alipayIotDeviceCancel(dynamic data){
    if(XFlutterUtils.isAndroid()){

      Map<String,Object> map={};
      map['operateType']='pop';

      if('opencardpay'==data){
        //会员支付
        XFlutterPluginUtils.memberPayAlipayIotSDK(XJsonUtils.obj2Json(map));
      }else if('opencard'==data){
        //会员登录
        XFlutterPluginUtils.memberCardAlipayIotSDK(XJsonUtils.obj2Json(map));
      }else{
        //普通支付
        XFlutterPluginUtils.commonPayAlipayIotSDK(XJsonUtils.obj2Json(map));
      }
    }
  }
  //支付宝碰一碰设备普通支付
  void _alipayIotDeviceCommonPay(dynamic data){
    if(XFlutterUtils.isAndroid()){
      //发起
      Map<String,Object> map={};
      map['operateType']='show';
      map['amount']='$data';
      //map['tradeNo']='100001001000';
      XFlutterPluginUtils.commonPayAlipayIotSDK(XJsonUtils.obj2Json(map));
    }
  }

  //支付宝碰一碰设备会员开卡
  void _alipayIotDeviceMemberCard(dynamic data){

    if(XFlutterUtils.isAndroid()){
      //发起
      //{"appId":"2021003107671848","providerId":"2088611935241475","templateId":"20240830000000005708166000300470","outString":{"group_id":"61FF8013A1FA494DBDCF718CBCB8E05B","company_id":"5ad586a8721e49518998aedef9fd3b5c"}}
      Map<String,Object> map={};
      map['operateType']='show';
      map['itemAppId']=alipayIotServiceInfoMap['appId'];
      map['templateId']=alipayIotServiceInfoMap['templateId'];
      map['providerId']=alipayIotServiceInfoMap['providerId'];
      map['outString']=XJsonUtils.obj2Json(alipayIotServiceInfoMap['outString']);
      XFlutterPluginUtils.memberCardAlipayIotSDK(XJsonUtils.obj2Json(map));
    }
  }
  //支付宝碰一碰设备会员支付
  void _alipayIotDeviceMemberPay(dynamic data){
    if(XFlutterUtils.isAndroid()){
      //发起
      Map<String,Object> map={};
      map['operateType']='show';
      map['itemAppId']=alipayIotServiceInfoMap['appId'];
      map['templateId']=alipayIotServiceInfoMap['templateId'];
      map['providerId']=alipayIotServiceInfoMap['providerId'];
      map['outString']=XJsonUtils.obj2Json(alipayIotServiceInfoMap['outString']);
      XFlutterPluginUtils.memberPayAlipayIotSDK(XJsonUtils.obj2Json(map));
    }
  }

  void reSetReceiveNativeMessageCallback_XSDKFlutterPlugin(){
    if(XFlutterUtils.isAndroid()){
      XFlutterPluginUtils.setReceiveNativeMessageCallback((resultMap) {
        XLogUtils.printLog("---!!!XFlutterPluginUtils接收原生android通知flutter消息=$resultMap");

        //{"type":"XSecondScreen","data":"{\"type\":\"getOfflineShopCart\"}"}
        String type=resultMap['type']??'';
        if(type=='XSecondScreen'){
          Map<String,dynamic> data=XJsonUtils.json2Map(resultMap['data']);
          String t1=data['type']??'';
          if(t1=='getOfflineShopCart'){
            //第二屏幕需要获得购物车
            String sJson= SupportGetGoodItems.getOfflineShopCart();
            Map<String,dynamic> map1={};
            map1['type']='shopcart';
            map1['data']=sJson;
            XFlutterPluginUtils.sendMsgToSecondScreen(XJsonUtils.obj2Json(map1));

          }else if(t1=='getH5SaveValue'){
            //
            String key=data['data']??'';
            _handle_getH5SaveValue(key,isSecondScreen:true);
          }
        }else if(type=='AlipayIot_init'){
          //支付宝碰一碰硬件初始化
          String dataJson=resultMap['data']??'';
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot初始化返回:$dataJson');

        }else if(type=='AlipayIot_commonPay'){
          //支付宝碰一碰硬件 普通支付
          String dataJson=resultMap['data']??'';
          runJSFunction(jsFunction_getAppValue('BPaaSCashier',dataJson));

          XLogUtils.printLog('---AlipayIot_commonPay=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot_commonPay返回:$dataJson');

        }else if(type=='AlipayIot_memberPay'){
          //支付宝碰一碰硬件 会员支付
          String dataJson=resultMap['data']??'';
          runJSFunction(jsFunction_getAppValue('BPaaSNfcMemberPay',dataJson));

          XLogUtils.printLog('---AlipayIot_memberPay=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot_memberPay返回:$dataJson');

        }else if(type=='AlipayIot_memberCard'){
          //支付宝碰一碰硬件 会员开卡登录
          String dataJson=resultMap['data']??'';
          runJSFunction(jsFunction_getAppValue('BPaaSNfcMember',dataJson));

          XLogUtils.printLog('---AlipayIot_memberCard=$dataJson');
          //阿里云日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---AlipayIot_memberCard返回:$dataJson');

        }
      });
    }
  }

  @override
  void onDestroy() {
    super.onDestroy();
    webServer?.close();
  }

  //
  @override
  Future<void> handleReceiveJsSendMsg(dynamic jsonStr) async {
    try{
      Map<String,dynamic> jsMsgMap=XJsonUtils.json2Map(jsonStr);
      String type=jsMsgMap['type'];
      //h5封装方法约定为json字符串
      dynamic data=jsMsgMap['data'];

      if('h5LoginSucceedNotify'==type){
        //h5登录成功通知 ok
        _handle_h5LoginSucceedNotify(data);
      }else if('cmp_alipayspeedissue'==type){
        XLogUtils.printLog('---h5通知更新支付宝碰一碰模板参数,data=$data');
        //阿里云日志
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---h5通知更新支付宝碰一碰模板参数:${XJsonUtils.obj2Json(data)}');

        _updateAlipayIotDeviceServiceInfo(data);
      }else if('BPaaSCashier'==type){
        XLogUtils.printLog('---h5通知支付宝碰一碰设备普通支付,data=$data');
        //阿里云日志
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---h5通知支付宝碰一碰设备普通支付:${XJsonUtils.obj2Json(data)}');

        _alipayIotDeviceCommonPay(data);
      }else if('BPaaSNfcMember'==type){
        XLogUtils.printLog('---h5通知支付宝碰一碰设备会员开卡,data=$data');
        //阿里云日志
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---h5通知支付宝碰一碰设备会员开卡:${XJsonUtils.obj2Json(data)}');

        _alipayIotDeviceMemberCard(data);
      }else if('BPaaSNfcMemberPay'==type){
        XLogUtils.printLog('---h5通知支付宝碰一碰设备会员支付,data=$data');
        //阿里云日志
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---h5通知支付宝碰一碰设备会员支付:${XJsonUtils.obj2Json(data)}');

        _alipayIotDeviceMemberPay(data);
      }else if('BPaaSCashierCancel'==type){
        XLogUtils.printLog('---h5通知支付宝碰一碰设备取消data=$data');
        //阿里云日志
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_initAlipayIot(), '---h5通知支付宝碰一碰设备取消:${XJsonUtils.obj2Json(data)}');

        _alipayIotDeviceCancel(data);
      }else if('openNewWebView'==type){
        //打开新webview页面,用完关闭

        Map<String,dynamic> dMap;
        if(data is String){
          dMap=XJsonUtils.json2Map(data);
        }else{
          dMap=data;
        }

        startPage(OtherWebViewStatePage(
          title: dMap['title']??'睿本云HD',
          webUrl: dMap['webUrl']??'https://www.reabam.com',
          jsonData: dMap['jsonData'],
        ),
            resultCallback: (res){
              if(res!=null){
                XLogUtils.printLog('---openNewWebView,返回res=${XJsonUtils.obj2Json(res)}');

                if(res is String){
                  runJSFunction(jsFunction_getAppValue('openNewWebView',res));
                }else{
                  runJSFunction(jsFunction_getAppValue('openNewWebView',XJsonUtils.obj2Json(res)));
                }
              }
            }
        );
      }else if('ThemeColors'==type){
        //颜色方案

        try{
          XLogUtils.printLog('---ThemeColors=${XJsonUtils.obj2Json(data)}');
          int index='$data'.toString().indexOf('&');
          if(index!=-1){
            String themeColor='$data'.substring(0,index);
            XLogUtils.printLog('---ThemeColors=$themeColor');
            if(XStringUtils.isEmpty(themeColor)){
              themeColor='0,0,0';
            }
            List<String> cL=themeColor.split(',');
            RBColors.reabamColor4=Color.fromARGB(255, int.tryParse(cL[0])??0, int.tryParse(cL[1])??0, int.tryParse(cL[2])??0);
            XColorUtils.appMainColor=RBColors.reabamColor4;

          }
        }catch(e){
          XLogUtils.printLog('---主题色,报错:$e');
        }

        //更新app
        _handle_checkAppUpdate();

      }else if('openSecondaryScreen'==type){
        XLogUtils.printLog("---h5调用openSecondaryScreen,key=$data");
        if(XFlutterUtils.isAndroid()){
          if("SO"=='$data'){
            //开启
            XLogUtils.printLog("---h5调用开启分屏");
            XFlutterPluginUtils.openSecondScreen(RBConfigs.secondScreenWebUrl2);
          }else if("SR"=='$data'){
            //刷新
            XLogUtils.printLog("---h5调用刷新分屏");
            XFlutterPluginUtils.updateSecondScreen();
          }
        }

      }else if('h5UploadDeviceSettingInfo'==type){
        XLogUtils.printLog("---h5通知更改设备配置,上传设备信息,h5UploadDeviceSettingInfo");
        RBBaseApi.uploadDeviceSettingInfo(false);
      }else if('skipPage1'==type){
        //跳转设置界面ok
        XLogUtils.printLog('---跳转设置界面');
        _handle_goToSettingPage();

      }else if('backToScreen'==type){
        //返回系统桌面
        if(XFlutterUtils.isAndroid()){
          XFlutterPluginUtils.goBackToScreen();
        }else{
          XFlutterUtils.closeApp();
        }
      }else if('closeApp'==type){
        //关闭App
        XFlutterUtils.closeApp();
      }else if('getCpuMemoryInfo'==type){
        //当前cpu内存使用情况
        Map<String,dynamic> cpuMemInfo= await XFlutterUtils.getCpuMemInfo();
        runJSFunction(jsFunction_getAppValue('getCpuMemoryInfo',cpuMemInfo['showUseInfo']??''));
      }else if('getAppVersionCode'==type){
        //获得版本号 ok
        runJSFunction(jsFunction_getAppValue('appVersion',RBConfigs.versionName));
      }else if('getAppVersion'==type){
        //获得版本号 ok
        runJSFunction(jsFunction_getAppValue('appVersion',RBConfigs.versionName));
      }else if('getSystemType'==type){
        //获得系统类型
        String systemName=XFlutterUtils.getSystemName();

        if('Android'==systemName){
          runJSFunction(jsFunction_getAppValue('getSystemType','FlutterAndroid'));
        }else if('iOS'==systemName){
          runJSFunction(jsFunction_getAppValue('getSystemType','FlutteriOS'));
        }else if('Windows'==systemName){
          runJSFunction(jsFunction_getAppValue('getSystemType','FlutterWindows'));
        }else if('MacOS'==systemName){
          runJSFunction(jsFunction_getAppValue('getSystemType','FlutterMacOS'));
        }else{
          runJSFunction(jsFunction_getAppValue('getSystemType','Other'));
        }

      }else if('getSystemAndDeviceType'==type){
        //获得系统类型
        String systemName=XFlutterUtils.getSystemName();
        //
        Map<String, dynamic> deviceInfo= await XFlutterUtils.getDeviceInfo();
        String brand=deviceInfo['brand'];
        String model=deviceInfo['model'];

        Map<String,dynamic> mapR={};
        mapR['framework']='Flutter';
        mapR['system']=systemName; //Android,iOS,Windows,MacOS
        mapR['brand']=brand; //设备品牌,如:SUNMI
        mapR['model']=model; //设备型号,如:T1,T2,T2s

        runJSFunction(jsFunction_getAppValue('getSystemAndDeviceType','${XJsonUtils.obj2Json(mapR)}'));

      }else if('checkAppUpdate'==type){
        //检测app更新
        _handle_checkAppUpdate();
      }else if('h5SendLogToAliYun'==type){
        //提供阿里云日志给h5使用
        _handle_h5SendLogToAliYun(data);
      }else if('goToScanActivity'==type){
        //跳转扫描二维码界面ok
        _handle_goToScanActivity();
      }else if('getH5SaveValue'==type){
        //获得通用存储key对应的值ok
        _handle_getH5SaveValue(data);
      }else if('setH5SaveValue'==type){
        //通用保存ok
        _handle_setH5SaveValue(data);
      }else if('getDeviceType'==type){
        //判断是否商米机,返回机器类型
        _handle_getDeviceType();
      }else if('getIsShangMiDevice'==type){
        //判断是否商米机,返回机器类型
        _handle_getIsShangMiDevice();
      }else if('getOfflineGoodsDBVersion'==type){
        //获得离线商品数据库版本号
        _handle_getOfflineGoodsDBVersion();
      }else if('openCashBox'==type){
        //打开钱箱 ok
        _handle_openCashBox();
      }else if('getWeighValue'==type){
        //打开电子秤原生界面
        //toast('打开称重界面');
        _open_chengzhong(data);
      }else if('offlineGoodType'==type){
        //获得离线数据:商品分类 ok
        String gtJson=SupportGetGoodItems.getOfflineGoodType();
        runJSFunction(jsFunction_getOfflineDataCallback('offlineGoodType',gtJson));
      }else if('getPayTypeList'==type){
        //获得离线数据:支付方式 ok
        String pJson=SupportGetGoodItems.getPayTypeList();
        runJSFunction(jsFunction_getOfflineDataCallback('offlinePayType',pJson));
      }else if('getOfflineShopCart'==type){
        //获得离线数据:购物车 ok
        String sJson=SupportGetGoodItems.getOfflineShopCart();
        runJSFunction(jsFunction_getOfflineDataCallback('offlineShopcart',sJson));
      }else if('saveOfflineShopCart'==type){
        //保存购物车离线数据 ok
        SupportGetGoodItems.saveOfflineShopCart(data);
      }else if('offlineGoodItems'==type){
        //获得离线数据:商品分页数据(现作为搜索,支持重量码,金额码) ok
        SupportGetGoodItems.searchGoodItems(
            this,
            data,
            callback:(Map<String,dynamic> result) {

          String json=XJsonUtils.obj2Json(result);

          //XLogUtils.printLog('---测试数据库结果json=$json');
          //判断字符串长度
          int jsonLength=json.length;

          //分割字符串长度算法
          int cutLength=800000;
          //分割总数
          int totalLines=0;
          if(jsonLength>(cutLength+1)){
            //需要分割
            XLogUtils.printLog('---需要分割');

            int cutNum= (jsonLength/cutLength).truncate();
            totalLines=cutNum;

            //
            if(jsonLength%cutLength!=0){
              totalLines=cutNum+1;
            }
            //cutNum=2
            for(int i=0;i<cutNum;i++){
              String key1='$i';
              String json1=json.substring(i*cutLength,(i+1)*cutLength);
              XLogUtils.printLog('---key1=$key1, totalLines=$totalLines,json1=$json1');
              runJSFunction(jsFunction_offlineGoodItems_longJson('offlineGoodItemsCut2',json1,key1,'$totalLines'));
            }

            //
            if(jsonLength%cutLength!=0){
              String key1='$cutNum';
              String json1=json.substring(cutNum*cutLength);
              XLogUtils.printLog('---结尾 key1=$key1, totalLines=$totalLines,json1=$json1');
              runJSFunction(jsFunction_offlineGoodItems_longJson('offlineGoodItemsCut2',json1,key1,'$totalLines'));
            }

          }else{
            //不需要分割
            XLogUtils.printLog('---不需要分割');
            runJSFunction(jsFunction_getAppValue('offlineGoodItems',json));
          }
        }
        );
      }else if('getItemListCallbackSimpleJson'==type){
        //获得离线数据:商品分页数据(异步处理) ok
        SupportGetGoodItems.getGoodItems_simpleJson(data,(json){
          XLogUtils.printLog('---测试数据库结果json=$json');
          //判断字符串长度
          int jsonLength=json.length;

          //分割字符串长度算法
          int cutLength=1000000;
          //分割总数
          int totalLines=0;
          if(jsonLength>(cutLength+1)){
            //需要分割
            XLogUtils.printLog('---需要分割');

            int cutNum= (jsonLength/cutLength).truncate();
            totalLines=cutNum;

            //
            if(jsonLength%cutLength!=0){
              totalLines=cutNum+1;
            }
            //cutNum=2
            for(int i=0;i<cutNum;i++){
              String key1='$i';
              String json1=json.substring(i*cutLength,(i+1)*cutLength);
              runJSFunction(jsFunction_offlineGoodItems_longJson('offlineGoodItemsCut2',json1,key1,'$totalLines'));
            }

            //
            if(jsonLength%cutLength!=0){
              String key1='$cutNum';
              String json1=json.substring(cutNum*cutLength);
              runJSFunction(jsFunction_offlineGoodItems_longJson('offlineGoodItemsCut2',json1,key1,'$totalLines'));
            }

          }else{
            //不需要分割
            XLogUtils.printLog('---不需要分割');
            runJSFunction(jsFunction_getAppValue('offlineGoodItems',json));
          }
        });
      }else if('getGoodItemDetail'==type){
        //获得离线数据:商品详情 ok
        SupportGetGoodItems.getGoodItemDetail(data,(Map<String,dynamic> result) {
          String json1=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getAppValue('getGoodItemDetail',json1));
        });
      }else if('getSpecList'==type){
        //获得离线数据:规格多个
        SupportGetGoodItems.getSpecList(data,(Map<String,dynamic> result){
          String json1=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getOfflineDataCallback('offlineSpecItems',json1));
        });
      }else if('getSpecItem'==type){
        //获得离线数据:规格1个
        SupportGetGoodItems.getSpecItem0(data,(Map<String,dynamic> result){
          String json1=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getOfflineDataCallback('offlineGoodItemsSpec',json1));
        });
      }else if('speak'==type){
        //文字转语音
        _handle_speak(data);
      }else if('needPrint'==type){
        //通知打印ok
        SupportControlDevices.needPrint(this,data);
      }else if('saveOfflineOrder'==type){
        //保存离线下单收银订单 ok
        supportOfflineOrder.saveOfflineOrder(data);
      }else if('delOfflineOrder'==type){
        //删除离线下单收银订单(数据库) ok
        supportOfflineOrder.delOfflineOrder(data);
      }else if('getOfflineOrderList'==type){
        //获得离线数据:下单收银订单列表分页数据(异步处理)(数据库)ok
        supportOfflineOrder.getOfflineOrderList(data);
      }else if('savePendingOrder'==type){
        //保存挂单(数据库)ok
        supportOfflineOrder.savePendingOrder(data);
      }else if('delPendingOrder'==type){
        //删除挂单(数据库) ok
        supportOfflineOrder.delPendingOrder(data);
      }else if('delAllPendingOrder'==type){
        //删除所有挂单(数据库)ok
        supportOfflineOrder.delAllPendingOrder();
      }else if('getOfflinePendingOrderList'==type){
        //获得挂单订单列表 旧
        supportOfflineOrder.getOfflinePendingOrderList(data);
      }else if('getPendingOrderListWithItems'==type){
        //获得挂单订单列表(数据库) 新
        supportOfflineOrder.getPendingOrderListWithItems(data);
      }else if('getPendingOrderDetail'==type){
        //获得挂单订单详情
        supportOfflineOrder.getPendingOrderDetail(data);
      }else if('getOfflinePendingOrderTotalCount'==type){
        //获得挂单订单列表总数量(数据库)ok
        supportOfflineOrder.getOfflinePendingOrderTotalCount();
      }else if('initConfig'==type){
        //h5接口缓存
        XLogUtils.printLog('---收到h5通知接口缓存,initConfig: $data');
        supportH5ApiCache.h5ApiRequestCache(data);
      }else if('uploadOrder2'==type){
        //上传订单 订单上传 2.0k
        Future(()async{

          Map<String,dynamic> result= SupportUploadOrderAndPay.uploadOrderTask2(data);
          String json=XJsonUtils.obj2Json(result);
          dynamic r1= await runJSFunctionForResult(jsFunction_getAppValue('uploadOrder',json));
          XLogUtils.printLog('---r1=$r1');
          if(r1!=200){
            //日志
            XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_callH5Fail(),'调用javascript:getAppValue无返回,json=$json');
          }else{
            //重试一次
            r1= await runJSFunctionForResult(jsFunction_getAppValue('uploadOrder',json));
            if(r1!=200){
              //日志
              XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_callH5Fail(),'调用javascript:getAppValue重试无返回,json=$json');
            }
          }

        });

      }else if('checkOrderUpload'==type){
        //h5检查订单是否已追平
        SupportUploadOrderAndPay.checkOrderUpload(data,(Map<String,dynamic> result){
          String json=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getAppValue('checkOrderUpload',json));
        });
      }else if('checkUnUploadOrderCnt'==type){
        //获得未上传订单数,h5用于监控上传服务器
        SupportUploadOrderAndPay.checkUnUploadOrderCnt(this);
      }else if('getUploadOrderList'==type){
        //获得本地未追平订单ok
        SupportUploadOrderAndPay.getUploadOrderList(data,(Map<String,dynamic> result){
          String json=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getAppValue('getUploadOrderList',json));
        });
      }else if('saveOrderShoppingcart'==type){
        //保存购物车 ok
        SupportUploadOrderAndPay.saveOrderShoppingcart(data,(Map<String,dynamic> result){
          String json=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getAppValue('saveOrderShoppingcart',json));
        });
      }else if('getOrderShoppingcart'==type){
        //获得购物车ok
        XLogUtils.printLog('---getOrderShoppingcart=$data');
        SupportUploadOrderAndPay.getOrderShoppingcart(data,(Map<String,dynamic> result){
          String json=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getAppValue('getOrderShoppingcart',json));
        });
      }else if('retryPosOrder'==type){
        //刷新本地未追平订单, POS传输业务重试(批量/单个都支持) ok
        XLogUtils.printLog('---刷新本地未追平订单 retryPosOrder,orderNo=$data');
        SupportUploadOrderAndPay.retryPosOrder(data,(Map<String,dynamic> result){
          String json=XJsonUtils.obj2Json(result);
          runJSFunction(jsFunction_getAppValue('retryPosOrder',json));
        });
      }else if('getShoppingCartItemsPromotionPlanIds'==type){
        //获得购物车商品对应的促销planIds(非排除,按商品,分类,品牌,系列,...)
        XLogUtils.printLog('---getShoppingCartItemsPromotionPlanIds=$data');
        supportOfflineCuxiao.getShoppingCartItemsPromotionPlanIds(data);
      }else if('getShoppingCartItemsPromotionJsons'==type){
        //获得planIds对应的促销json
        XLogUtils.printLog('---getShoppingCartItemsPromotionJsons=$data');
        supportOfflineCuxiao.getShoppingCartItemsPromotionJsons(data);
      }else if('getShoppingCartItemTimedPromotions'==type){
        //获得商品的秒杀促销
        XLogUtils.printLog('---getShoppingCartItemTimedPromotions=$data');
        supportOfflineCuxiao.getShoppingCartItemTimedPromotions(data);
      }else if('getMutexPlans'==type){
        //互斥促销
        XLogUtils.printLog('---getMutexPlans=$data');
        supportOfflineCuxiao.getMutexPlans(data);
      }else if('getShoppingCartItemListPromotions'==type){
        //获得促销商品清单  一般是赠品、换购、凑单入口 返回分页的促销品信息
        XLogUtils.printLog('---getShoppingCartItemListPromotions=$data');
        supportOfflineCuxiao.getShoppingCartItemListPromotions(data);
      }else if('getOrderPromotions'==type){
        //获得订单的所有整单促销
        XLogUtils.printLog('---getOrderPromotions');
        supportOfflineCuxiao.getOrderPromotions();
      }else if('getOrderItemsPromotionSpecIds'==type){
        //获得整单指定商品(按商品,品牌,系列,分类)条件,是否排除,整单planId, 返回符合条件的商品规格id
        XLogUtils.printLog('---getOrderItemsPromotionSpecIds=$data');
        supportOfflineCuxiao.getOrderItemsPromotionSpecIds(data);
      }else if('CreateOrderPayRequest'==type){
        //支付兜底,插入订单支付请求ID
        XLogUtils.printLog('---CreateOrderPayRequest=$data');
        supportRepayOrder.createOrderPayRequest(data);
      }else if('UpdateOrderPayRequest'==type){
        //支付兜底,更新订单支付状态
        XLogUtils.printLog('---UpdateOrderPayRequest=$data');
        supportRepayOrder.updateOrderPayRequest(data);
      }else if('GetOrderPayRequest'==type){
        //支付兜底,获取订单支付
        XLogUtils.printLog('---GetOrderPayRequest=$data');
        supportRepayOrder.getOrderPayRequest(data);
      }else if('downloadOfflineDBFileUrl'==type){
        //h5调用原生方法通知获取返回的离线数据文件下载路径,下载 ok
        XLogUtils.printLog('---downloadOfflineDBFileUrl=$data');
        SupportDownloadDBFile.downloadOfflineDBFileUrl(data,(res){
          String code=res['code'];
          int type=res['type'];
          if(code=='-1'){
            runJSFunction(jsFunction_notifyFailedDownloadOfflineData());
          }else{

            if(type==1){
              //开始下载支付方式
            }else if(type==2){
              //开始下载商品分类
            }else if(type==3){
              //开始下载离线文件
            }else if(type==4){
              //开始处理离线文件
            }else if(type==10){
              //下载完成
              String companyId=XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
              String time=XSharePreferencesUtils.getString("XDownloadLastTimeReabamPos_DB$companyId");
              runJSFunction(jsFunction_getOfflineDataCallback('goodscacheTime',time));
              runJSFunction(jsFunction_notifyCompleteDownloadOfflineData());
            }
          }

        });
      }else if('downloadOfflineData'==type){
        //按钮触发请求下载离线数据,发起下载,等待websocket通知h5获得返回文件路径 ok
        XLogUtils.printLog('---downloadOfflineData');

        //发起下载,等待websocket通知h5,获得返回文件路径
        //通知h5开始下载离线数据
        runJSFunction(jsFunction_notifyStartDownloadOfflineData());
        //
        RBBaseApi.downloadDBFileWaitH5CallbackFileUrl(
            succeed: (dynamic response, Map<String, dynamic> responseMap, Map<String, dynamic> headersResponse) {
            },
            failed: (String code, String msg) {
              XLogUtils.printLog('---发起离线数据文件获得url: code:$code,msg=$msg');
              //通知h5下载离线数据失败
              runJSFunction(jsFunction_notifyFailedDownloadOfflineData());
            });

      }else if('h5webSocketUpdateGoodItemsDB'==type){
        //websocket通知h5商品增量更新
        XLogUtils.printLog('---h5webSocketUpdateGoodItemsDB=$data');
        SupportDownloadDBFile.h5webSocketUpdateGoodItemsDB(this,data);
      }else if('downloadOfflineDBPromotionFileUrl'==type){
        //h5调用原生方法下载全量促销, 过期旧方法,新促销下载废弃,兼容旧版
        XLogUtils.printLog('---downloadOfflineDBPromotionFileUrl=$data');
        SupportDownloadDBFile.downloadOfflineDBPromotionFileUrl(this,data);
      }else if('h5webSocketUpdatePromotion'==type){
        //websocket通知h5促销增量或全量更新
        XLogUtils.printLog('---h5webSocketUpdatePromotion=$data');
        SupportDownloadDBFile.h5webSocketUpdatePromotion(this,data);
      }else if('selectAndUploadPhoto'==type){
        //生产端 选择和上传图片到又拍云
        XLogUtils.printLog('---selectAndUploadPhoto=$data');
        supportHandlePhoto.selectAndUploadPhoto(data);
      }else if('aiRecognitionImage'==type){
        //ai识别商品
        XLogUtils.printLog('---aiRecognitionImage');
        supportHandlePhoto.aiRecognitionImage();
      }

    }catch(error,stacktrace){
      XLogUtils.printLog('---error$error,stacktrace=$stacktrace');
    }
  }

  //////////////////////////////////////////////////

  //原生调用js方法
  String jsFunction_getAppValue(String key,String value){
    return "javascript:getAppValue('$key','$value')";
  }
  String jsFunction_getOfflineDataCallback(String key,String json){
    return "javascript:getOfflineDataCallback('$key','$json')";
  }
  String jsFunction_offlineGoodItems_longJson(String key,String json,String key1,String totalLines){
    return "javascript:getOfflineDataCallback('$key','$json','$key1','$totalLines')";
  }

  String jsFunction_getScanValue(String value){
    return "javascript:getScanValue('$value')";
  }
  String jsFunction_getweigh(double value){
    return "javascript:getweigh_app('$value')";
  }


  //通知h5下载离线数据失败
   String jsFunction_notifyFailedDownloadOfflineData(){
    return "javascript:notifyFailedDownloadOfflineData()";
  }
  //通知h5开始下载离线数据
   String jsFunction_notifyStartDownloadOfflineData(){
    return "javascript:notifyStartDownloadOfflineData()";
  }
  //通知h5下载离线数据成功
   String jsFunction_notifyCompleteDownloadOfflineData(){
    return "javascript:notifyCompleteDownloadOfflineData()";
  }

  //////////////////////////////////////////////////

  //文字转语音
  void _handle_speak(dynamic data){
    try{
      String speakMsg='请$data号取餐';
      XTTSUtils.speak(speakMsg);
      //叫号屏
      if(SupportControlDevices.socketTV!=null){
        Map ttsMsg={
          'msgType':'baiduTTS',
          'speakMsg':speakMsg,
        };
        XBaseQueueMessage msg=XBaseQueueMessage(
          msgId: '叫号屏_${XDateUtils.getCurrentTime_ms()}',
          message: ttsMsg,
          ip:SupportControlDevices.socketTV!.ip!,
          port:SupportControlDevices.socketTV!.port,
        );
        XSocketUtils.sendMsgToQueue(msg);
      }
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_speak'),'$e');
    }

  }


  //打开钱箱 ok
  void _handle_openCashBox() async{
    try{

      //商米内置打印机
      String systemName=XFlutterUtils.getSystemName();
      if('Android'==systemName){
        Map<String, dynamic> deviceInfo= await XFlutterUtils.getDeviceInfo();
        String brand=deviceInfo['brand'];
        XLogUtils.printLog("---设备品牌类型:$brand");//SUNMI
        if(XStringUtils.equalsIgnoreCase('SUNMI', brand)){
          XFlutterPluginUtils.openDrawerByShangMi();
        }else{
          //如:中崎一体机
          XFlutterPluginUtils.openDrawer();
        }

      }

      //外置蓝牙打印机 (RK3288的内置串口不支持钱箱,没有相关命令,因此用外置打印机连接钱箱方法)
      XBaseQueueMessage msg = XBaseQueueMessage(
        msgId: 'ble_${XDateUtils.getCurrentTime_ms()}',
        isPriorityHandle:true,
        isOpenCashDrawerCommand:true,
      );
      XBluetoothBLEUtils.sendMsgToQueue(msg);
      //XSocketUtils.sendMsgToQueue(msg);


    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_openCashBox'),'$e');
    }
  }

  //获得离线商品数据库版本号
  void _handle_getOfflineGoodsDBVersion(){
    try{
      String companyId=XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
      int version= XSharePreferencesUtils.getInt(RBConfigs.SP_offlineDBGoodsVersion2+companyId);

      XLogUtils.printLog('---获得离线商品数据库版本号= $version');

      runJSFunction(jsFunction_getAppValue('getOfflineGoodsDBVersion','$version'));
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_getOfflineGoodsDBVersion'),'$e');
    }
  }

  //判断是否商米机, 返回机器类型
  void _handle_getIsShangMiDevice() async{

    try{
      String systemName=XFlutterUtils.getSystemName();
      if('Android'==systemName){
        Map<String, dynamic> deviceInfo= await XFlutterUtils.getDeviceInfo();
        String brand=deviceInfo['brand'];
        XLogUtils.printLog("---设备品牌类型:$brand");//SUNMI
        if(XStringUtils.equalsIgnoreCase('SUNMI', brand)){
          runJSFunction(jsFunction_getAppValue('getIsShangMiDevice','true'));
        }else{
          runJSFunction(jsFunction_getAppValue('getIsShangMiDevice','false'));
        }

      }else{
        //其他
        runJSFunction(jsFunction_getAppValue('getIsShangMiDevice','false'));
      }
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_getIsShangMiDevice'),'$e');
      runJSFunction(jsFunction_getAppValue('getIsShangMiDevice','false'));
    }

  }

  //判断是否商米机, 返回机器类型
  void _handle_getDeviceType() async{

    try{
      String systemName=XFlutterUtils.getSystemName();
      if('Android'==systemName){
        Map<String, dynamic> deviceInfo= await XFlutterUtils.getDeviceInfo();
        String brand=deviceInfo['brand'];
        XLogUtils.printLog("---设备品牌类型:$brand");//SUNMI
        runJSFunction(jsFunction_getAppValue('getDeviceType',brand));
      }else{
        //其他
        runJSFunction(jsFunction_getAppValue('getDeviceType',systemName));
      }
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_getDeviceType'),'$e');
      runJSFunction(jsFunction_getAppValue('getDeviceType','unknown'));
    }

  }

  //跳转设置界面
  void _handle_goToSettingPage() async{
    try{
      RBConfigs.localIP=await XWifiUtils.getWifiIP();
      //XLogUtils.printLog('---localIP=${RBConfigs.localIP}');

      startPage(
          DeviceSettingStatePage(),
          resultCallback: (dynamic result){
            if(result!=null){
              //更新设备记录设置
              SupportControlDevices.initAllDevicesNoteSetting();
              //上传设备设置记录
              RBBaseApi.uploadDeviceSettingInfo(false);
            }
          }
      );
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_goToSettingPage'),'$e');
    }
  }



  //跳转扫描界面
  void _handle_goToScanActivity() async{
    try{
      startPage(
          ScanQrCodeStatePage(),
          resultCallback: (dynamic result){
            if(result!=null){
              //扫描返回
              String scanValue=result;
              XLogUtils.printLog('---扫描返回=$scanValue');
              //调用js中的函数：
              runJSFunction(jsFunction_getScanValue(scanValue));
            }
          }
      );
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_goToScanActivity'),'$e');
    }
  }

  //检查版本升级
  void _handle_checkAppUpdate(){

    if(XFlutterUtils.isAndroidOriOSSystem()){
      //
      String appCode='';
      if(XFlutterUtils.isAndroid()){
        //'flutter_pos_android',

        if(RBConfigs.versionType==VersionType.baodaoVersion){
          //包道
          appCode='baodao_hd_android';
        }else{
          appCode='reabam_hd_android';
        }

      }else{
        //iOS

        if(RBConfigs.versionType==VersionType.baodaoVersion){
          //包道
          appCode='baodao_hd_ios';
        }else{
          appCode='reabam_hd_ios';
        }
      }

      RBBaseApi.checkAppVersionUpdate(
        appCode: appCode,
        succeed: (ResponseCheckAppUpdate response,Map<String,dynamic> responseMap,Map<String,dynamic> headersResponse){

          BeanUpdateAppVersionData? data=response.data;
          if (data!=null){
            BeanUpdateAppVersionInfo? info=data.info;
            if (info!=null){
              try{
                //最新版本
                int sversion=int.tryParse('${info.version}')??0;
                XLogUtils.printLog('---服务端最新版本=$sversion');
                //当前版本
                int cversion=RBConfigs.version;
                if (sversion>cversion){
                  //
                  startPage(UpdateAPPStatePage(info));
                }

              }catch (e){
                XLogUtils.printLog('---checkAppVersionUpdate报错: $e');
              }

            }
          }
        },
        failed: (String code,String msg){},
      );
    }
  }


  //提供阿里云日志给h5使用
  void _handle_h5SendLogToAliYun(dynamic data){

    try{
      Map<dynamic,dynamic> map={};

      if(data is String){
        map=XJsonUtils.json2Map(data);
      }else if(data is Map){
        map=data;
      }

      String orderNo=map['orderNo']==null?'':map['orderNo'].toString();
      String log=map['log']==null?'':map['log'].toString();

      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_H5(orderNo),log);
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_h5SendLogToAliYun'),'$e');
    }

  }
  //称重商品,打开称重界面
  void _open_chengzhong(dynamic data){

    XLogUtils.printLog('----_open_chengzhong');

    try{
      Map<String,dynamic> map={};

      if(data is String){
        map=XJsonUtils.json2Map(data);
      }else{
        map=data;
      }
      XLogUtils.printLog('----_open_chengzhong,map=$map');

      startPage(ChengzhongStatePage(
          XJsonUtils.obj2Json(map)),
          resultCallback: (dynamic result){
            toast('称重返回');

            //
            reSetReceiveNativeMessageCallback_XSDKFlutterPlugin();

            // XLogUtils.printLog('----重启分屏');
            // XFlutterPluginUtils.openSecondScreen(RBConfigs.secondScreenWebUrl2);
            // XFlutterPluginUtils.updateSecondScreen();

            if(result!=null){
              double czR=XNumberUtils.d2d(3, result);
              XLogUtils.printLog('--称重值返回=$czR');
              runJSFunction(jsFunction_getweigh(czR));
            }

          });


    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_open_chengzhong'),'$e');
      XLogUtils.printLog('$e');
    }

  }

  //h5登录成功通知
  void _handle_h5LoginSucceedNotify(dynamic data) async{
    XLogUtils.printLog('---h5LoginSucceedNotify,data= $data');

    try{
      LoginResponse response;
      if(data is String){
        response=LoginResponse.fromJson(XJsonUtils.json2Map(data));
      }else{
        response=LoginResponse.fromJson(data??{});
      }

      XLogUtils.printLog('---h5LoginSucceedNotify,response= ${response.toJson().toString()}');
      LoginBean? DataLine=response.data;
      DataLine ??= response.DataLine;

      XLogUtils.printLog('---data.tokenId= ${response.data?.tokenId},DataLine.tokenId= ${response.DataLine?.tokenId}');

      if(DataLine!=null){
        String? sysNo=DataLine.sysNo;
        XLogUtils.printLog('---h5LoginSucceedNotify,sysNo= $sysNo');
        XSharePreferencesUtils.saveString(RBConfigs.SP_sysNo,sysNo??"");

        String? serverAddress=DataLine.serverAddress;
        String? zuulServerAddress=DataLine.zuulServerAddress;
        String? tokenId=DataLine.tokenId;


        XLogUtils.printLog('---h5LoginSucceedNotify,serverAddress= $serverAddress,zuulServerAddress=$zuulServerAddress,tokenId=$tokenId');

        if (XStringUtils.isEmpty(serverAddress)
            ||!serverAddress!.startsWith(RegExp('http'))
        ){
          serverAddress ="http://127.0.0.1";
        }
        if (XStringUtils.isEmpty(zuulServerAddress)
            ||!zuulServerAddress!.startsWith(RegExp(r'http'))){
          zuulServerAddress ="http://127.0.0.1";
        }

        XSharePreferencesUtils.saveString(XConstants.SP_UserGroup,DataLine.companyId??"");

        XSharePreferencesUtils.saveString(RBConfigs.SP_companyId,DataLine.companyId??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_companyName,DataLine.companyName??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_companyCode,DataLine.companyCode??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_groupId,DataLine.groupId??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_userId, DataLine.fid??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_userName, DataLine.userName??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_userCode, DataLine.userCode??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_tokenId, tokenId??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_serverAddress, serverAddress??"");
        XSharePreferencesUtils.saveString(RBConfigs.SP_zuulServerAddress, zuulServerAddress??"");

        //本地ip
        runJSFunction(jsFunction_getAppValue('wifiIP','${RBConfigs.localIP}'));

        XLogUtils.printLog('---开始阿里云日志初始化');

        String appName='睿本云HD';
        if(RBConfigs.versionType==VersionType.baodaoVersion){
          appName=='包道HD';
        }
        //初始化阿里云日志
        RBBaseApi.initAliyunLog(appName);

        //初始化socket设备
        XSocketUtils.init();
        //初始化远程设备(快麦云设备)
        XRemoteDeviceUtils.init();
        //初始化蓝牙设备
        XBluetoothBLEUtils.init();
        //初始化usb设备
        XUsbUtils.init();
        //初始化usbSerial设备
        XUsbSerialUtils.init();

        //重新获取支付方式和商品分类
        RBBaseApi.initGetPayTypeAndGoodType();

        //更新设备记录设置
        SupportControlDevices.initAllDevicesNoteSetting();

        //启用web server api方式通讯
        //_startWebServer();

        //上传设备记录
        RBBaseApi.uploadDeviceSettingInfo(true);

        if(XFlutterUtils.isAndroid()){
          //商米机android 6.0
          XFlutterPluginUtils.manualSystemLoadLibrary('objectbox-jni');

          //开启分屏 分屏url
          String secondScreenURL='?tokenId=${DataLine.tokenId}&serv=${XJiamiUtils.encodeUrl(serverAddress)}';
          RBConfigs.secondScreenWebUrl2='${RBConfigs.secondScreenWebUrl}$secondScreenURL';
          XLogUtils.printLog('---分屏secondScreenURL=${RBConfigs.secondScreenWebUrl2}');
          XFlutterPluginUtils.openSecondScreen(RBConfigs.secondScreenWebUrl2);

        }

        XLogUtils.printLog('---开始数据库初始化,companyId=${DataLine.companyId}');
        //objectbox database
        await XObjectBoxUtils.create(this,DataLine.companyId??'default_db');

        //通知h5初始化db成功
        if(!XSharePreferencesUtils.getBool(RBConfigs.SP_Pos_CompanyId_Save_DB_Succeed+XSharePreferencesUtils.getString(RBConfigs.SP_companyId))){
          //  "javascript:getAppValue(key,value)"
          XLogUtils.printLog('---初始化db成功,companyId不存在离线数据');
          runJSFunction(jsFunction_getAppValue('initDBSucceed','false'));
        }else{
          //companyId存在离线数据库 "javascript:getAppValue(key,value)"
          XLogUtils.printLog('---初始化db成功,companyId存在离线数据');
          runJSFunction(jsFunction_getAppValue('initDBSucceed','true'));
        }
        //登录成功重新检测和处理未上传订单2.0
        SupportUploadOrderAndPay.loginInitCheckUnUploadOrderTaskX();

      }
    }catch(e){
      XLogUtils.printLog('---h5LoginSucceedNotify报错: $e');
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_h5LoginSucceedNotify'),'$e');
    }


  }



  //获得通用存储key对应的值
  void _handle_getH5SaveValue(String key,{bool isSecondScreen=false}){
    try{
      String value=XSharePreferencesUtils.getString(key+XSharePreferencesUtils.getString(RBConfigs.SP_companyId));
      if (XStringUtils.isEmpty(value)){
        value="{}"; //h5专用存json
        if('quickcash'==key || 'goodscache'==key || 'takeAway'==key){
          value='1';
        }
      }
      XLogUtils.printLog('---getH5SaveValue,key=$key, value=$value');
      if(isSecondScreen){
        //第二屏
        Map<String,dynamic> map1={};
        map1['type']='H5SaveValue';
        map1['data']={'key':key,'value':value};
        XFlutterPluginUtils.sendMsgToSecondScreen(XJsonUtils.obj2Json(map1));
      }else{
        //主屏
        runJSFunction(jsFunction_getAppValue(key,value));
      }

    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_getH5SaveValue'),'$e');
    }
  }
  //通用保存
  void _handle_setH5SaveValue(dynamic data){
    try{
      Map<String,dynamic> dataMap;
      if(data is String){
        dataMap=XJsonUtils.json2Map(data);
      }else{
        dataMap=data??{};
      }
      String key=(dataMap['key']??'sp_key')+XSharePreferencesUtils.getString(RBConfigs.SP_companyId);
      String value='${dataMap['value']}';//转字符串保存
      XSharePreferencesUtils.saveString(key, value);
    }catch(e){
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_trycache('_handle_setH5SaveValue'),'$e');
    }

  }



  @override
  void onNotifyWebViewLoadUrlError(int? errorCode, String? description, String? failingUrl) {
    //webview加载url失败通知
    XLogUtils.printLog("---webview加载url失败通知: failingUrl=$failingUrl");
    setState(() {
      isWebViewLoadFailShowCustomWidget=true;
    });

  }

  @override
  Widget getUrlLoadFailCustomWidget() {
    return XWidgetUtils.getWidgetGestureDetector(
        child: XWidgetUtils.getLayoutContainer(
          alignment:Alignment.center,
          backgroundColor: Colors.white,
          child: XWidgetUtils.getLayoutColumn(
              mainAxisSize:MainAxisSize.min,
              mainAxisAlignment:MainAxisAlignment.center,
              crossAxisAlignment:CrossAxisAlignment.center,
              children: [
                XImageUtils.getImageWidgetWithAsset(
                    'index_no_data_5.png',
                    width: 122,
                    height: 98
                ),
                XWidgetUtils.getWidgetText(
                  '网络不可用,请检查网络连接,点击刷新重试!',
                  padding: XWidgetUtils.getEdgeInsets(0, 10, 0, 0),
                )
              ]
          ),
        ),
        onTap: (){
          //加载失败自定义提示界面,点击重新加载
          XLogUtils.printLog("-----reLoadUrl");
          setState(() {
            isWebViewLoadFailShowCustomWidget=false;
            reLoadUrl(loadFailUrl);
          });
        }
    );
  }



}